/**
 * 
 */
package com.selfdriving.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.List;

import com.selfdriving.BuildConfig;
import com.selfdriving.dialog.ChoosePictureDialog;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;

/**
 * @author 王志强
 * @version [v1.0] 易伟思 since
 */
public class BitmapUtil {
	/**
	 * 上傳圖片最大畫素
	 */
	public static final int IMAGE_MAX_PIXEL = 200000;

	public static String path = Environment.getExternalStorageDirectory()
			+ "/RongDa/image/";

	public static Bitmap decodeFile(String file) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inDither = false; // Disable Dithering mode
		opts.inPurgeable = true; // Tell to gc that whether it needs free
									// memory, the Bitmap can be cleared
		opts.inInputShareable = true; // Which kind of reference will be used to
										// recover the Bitmap data after being
										// clear, when it will be used in the
										// future
		// bfOptions.inTempStorage=new byte[32 * 1024];

		return BitmapFactory.decodeFile(file, opts);
	}

	public static Bitmap decodeStream(InputStream is) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inDither = false; // Disable Dithering mode
		opts.inPurgeable = true; // Tell to gc that whether it needs free
									// memory, the Bitmap can be cleared
		opts.inInputShareable = true; // Which kind of reference will be used to
										// recover the Bitmap data after being
										// clear, when it will be used in the
										// future
		// bfOptions.inTempStorage=new byte[32 * 1024];

		return BitmapFactory.decodeStream(is, null, opts);
	}

	/**
	 * 以省記憶體的方式讀取本地資源的圖片
	 * 
	 * @param resId
	 * @return Bitmap
	 * 
	 * @author Fate
	 */
	public static Bitmap readBitmap(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		/*
		 * try {
		 * BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean
		 * (opt,true); } catch (IllegalArgumentException e) { // TODO
		 * Auto-generated catch block e.printStackTrace(); } catch
		 * (SecurityException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); } catch (IllegalAccessException e) { // TODO
		 * Auto-generated catch block e.printStackTrace(); } catch
		 * (NoSuchFieldException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 */

		InputStream is = context.getResources().openRawResource(resId);
		Bitmap bm = BitmapFactory.decodeStream(is, null, opt);
		SoftReference<Bitmap> softBitmap = new SoftReference<Bitmap>(bm);

		return softBitmap.get();
	}

	public static Bitmap getSamplingImage(String path) {
		return getSamplingImage(path, IMAGE_MAX_PIXEL);
	}

	/**
	 * 取得旋轉完後的縮圖
	 * 
	 * @param path
	 *            圖片路徑
	 * @param samplingSize
	 *            圖片縮放的解析度, 如 180 * 180
	 * @return 旋轉完後的縮圖
	 */
	public static Bitmap getSamplingImage(String path, int samplingSize) {
		FileInputStream in;
		try {
			in = new FileInputStream(path);

			int degree = getRotateDegree(path);

			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			o.inPreferredConfig = Bitmap.Config.RGB_565;
			BitmapFactory.decodeStream(in, null, o);
			in.close();

			int scale = 1;
			int tmp_width = o.outWidth;
			int tmp_height = o.outHeight;

			if (BuildConfig.DEBUG) {
				LogUtil.i("送入圖片原始資料, 寬 : " + tmp_width + " | 高 : " + tmp_height);
			}

			if (tmp_width == -1 || tmp_height == -1) {
				return null;
			}

			if (tmp_width * tmp_height > samplingSize) {
				while (true) {
					if (tmp_width * tmp_height < samplingSize)
						break;
					tmp_width /= 2;
					tmp_height /= 2;
					scale *= 2;
				}
			} else {
				scale = 1;
			}

			if (BuildConfig.DEBUG) {
				LogUtil.i("計算後之scale : " + scale);
			}

			Bitmap b = null;
			in = new FileInputStream(path);

			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			o2.inJustDecodeBounds = false;
			o2.inPreferredConfig = Bitmap.Config.RGB_565;
			try {
				b = BitmapFactory.decodeStream(in, null, o2);
			} catch (OutOfMemoryError ex) {
				LogUtil.e("getSamplingImage, OutOfMemoryError");
				in.close();
				System.gc();
				if (BuildConfig.DEBUG)
					ex.printStackTrace();
				return null;
			}

			if (degree != 0 && b != null) {
				LogUtil.i("圖片需要旋轉, degree : " + degree);
				Matrix matrix = new Matrix();
				matrix.postRotate(degree);
				try {
					Bitmap resizedBitmap = Bitmap.createBitmap(b, 0, 0,
							b.getWidth(), b.getHeight(), matrix, true);
					if (b != resizedBitmap) {
						b.recycle();
						b = resizedBitmap;
					}
				} catch (OutOfMemoryError ex) {
					LogUtil.e("getSamplingImage, OutOfMemoryError");
					if (BuildConfig.DEBUG)
						ex.printStackTrace();
					return null;
				}
			}

			in.close();
			System.gc();
			if (BuildConfig.DEBUG) {
				LogUtil.i("輸出圖片資料, 寬 : " + b.getWidth() + " | 高 : "
						+ b.getHeight() + " | scale: " + scale);
			}
			SoftReference<Bitmap> softBitmap = new SoftReference<Bitmap>(b);
			b = null;
			return softBitmap.get();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 取得圖片旋轉角度
	 * 
	 * @param path
	 * @return
	 * @throws IOException
	 */
	public static int getRotateDegree(String path) throws IOException {
		ExifInterface exifInterface;
		int rotate = ExifInterface.ORIENTATION_NORMAL;
		int degree = 0;
		exifInterface = new ExifInterface(path);
		rotate = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
				ExifInterface.ORIENTATION_NORMAL);
		switch (rotate) {
		case ExifInterface.ORIENTATION_ROTATE_90:
			degree = 90;
			break;
		case ExifInterface.ORIENTATION_ROTATE_180:
			degree = 180;
			break;
		case ExifInterface.ORIENTATION_ROTATE_270:
			degree = 270;
			break;
		default:
			degree = 0;
			break;
		}
		LogUtil.d("圖片旋轉角度：" + degree);
		return degree;
	}

	public static void doCrop(Context context, Uri fileUri, boolean isFromFile) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setType("image/*");

		List<ResolveInfo> list = context.getPackageManager()
				.queryIntentActivities(intent, 0);

		int size = list.size();
		LogUtil.e("size" + size);
		if (size == 0) {
			Toast.makeText(context, "Can not find image crop app",
					Toast.LENGTH_SHORT).show();

			return;
		} else {
			intent.setData(fileUri);

			intent.putExtra("outputX", 140);
			intent.putExtra("outputY", 140);
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("scale", true);
			intent.putExtra("return-data", true);

			if (size == 1) {
				Intent i = new Intent(intent);
				ResolveInfo res = list.get(0);
				i.setComponent(new ComponentName(res.activityInfo.packageName,
						res.activityInfo.name));

				((Activity) context).startActivityForResult(i,
						isFromFile ? ChoosePictureDialog.CROP_FROM_FILE
								: ChoosePictureDialog.CROP_FROM_CAMERA);
			} else {
				if (size == 2) {
					intent.putExtra("outputX", 120);
					intent.putExtra("outputY", 120);
					Intent i = new Intent(intent);
					ResolveInfo res = list.get(0);
					i.setComponent(new ComponentName(
							res.activityInfo.packageName, res.activityInfo.name));

					((Activity) context).startActivityForResult(i,
							isFromFile ? ChoosePictureDialog.CROP_FROM_FILE
									: ChoosePictureDialog.CROP_FROM_CAMERA);
				}
			}
		}
	}

	public static Bitmap comp(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 800f;// 这里设置高度为800f
		float ww = 480f;// 这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		isBm = new ByteArrayInputStream(baos.toByteArray());
		bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
	}

	public static Bitmap compressImage(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return bitmap;
	}

	public static Bitmap getimage(String srcPath) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 800f;// 这里设置高度为800f
		float ww = 480f;// 这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
	}
}